package com.sx.pipeline.ui.mine

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.View
import android.widget.RadioGroup
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.noober.background.view.BLEditText
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.config.RegisterType
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActJoinBusinessBinding
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.repos.http.res.UnitNameVO
import com.sx.pipeline.repos.http.res.UnitTypeVO
import com.sx.pipeline.ui.register.adapter.SelectUnitTypeAdapter
import com.sx.pipeline.utils.ItemDecorationUtils
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * @Author: YY
 * @Date: 2022/6/27
 * @Desc: 加入企业
 */
@Route(path = RoutePath.Main.JOIN_BUSINESS)
class JoinBusinessActivity: CYDataBindingBaseActivity<ActJoinBusinessBinding, JoinBusinessVM>
    (R.layout.act_join_business), View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    // 单位类型
    private lateinit var selectUnitTypeAdapter: SelectUnitTypeAdapter

    override fun initStatusBar() {
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(false).init()
    }

    override fun onClick(v: View) {
        when(v.id) {
            R.id.image_left_gray -> {
                finish()
            }
            R.id.sb_address -> {
                showProvincesDialog()
            }
            R.id.sb_unit_name -> {
                mViewModel.getUnitNameList()
            }
            R.id.tv_next_step -> {
                mViewModel.joinBusiness(findViewById<BLEditText>(R.id.ed_remark).text.toString())
            }
        }
    }


    override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {
        when(group.id) {
            R.id.rg_register_status -> {
                // 注册身份
                when (checkedId) {
                    mBinding.rbOperateUnit.id -> {
                        mViewModel.identityField.set( IdentityType.OPERATING_UNIT.code)
                    }
                    mBinding.rbBuildUnit.id -> {
                        mViewModel.identityField.set(IdentityType.BUILD_UNIT.code)
                    }
                    else -> {
                        mViewModel.identityField.set(IdentityType.SUPPLIER.code)
                    }
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.setVariable(BR.onCheckedChanged, this)
        mViewModel.identityField.set(IdentityType.OPERATING_UNIT.code)

        mViewModel.getUnitType()

    }

    override fun initViewObservable() {
        super.initViewObservable()
        // 单位类型
        setUnitTypeList()
        // 单位名称
        showUnitNameDialog()
    }

    /**
     * 单位类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setUnitTypeList() {

        mBinding.recyclerUnitType.addItemDecoration(
            ItemDecorationUtils(4, 6, 4, 6, 0)
        )
        mBinding.recyclerUnitType.layoutManager = FlexboxLayoutManager(this,
            FlexDirection.ROW , FlexWrap.WRAP)

        // 单位类型
        observe(mViewModel.unitTypeListEvent) {
            if (it.isNullOrEmpty()) {
            } else {
                // 单位类型id
                mViewModel.unitTypeIdsField.set(it[0].id.toString())
                // 单位类型名称
                mViewModel.unitTypeNameField.set(it[0].name)

                if (!this::selectUnitTypeAdapter.isInitialized) {
                    selectUnitTypeAdapter = SelectUnitTypeAdapter(it as MutableList<UnitTypeVO>, false)
                }
                mBinding.recyclerUnitType.adapter = selectUnitTypeAdapter
                // item点击事件
                selectUnitTypeAdapter.setOnItemClickListener { adapter, _, position ->
                    // 单选
                    selectUnitTypeAdapter.setSelectClickId(position)
                    val unitTypeVO = adapter.data[position] as UnitTypeVO
                    // 单位类型id
                    mViewModel.unitTypeIdsField.set(unitTypeVO.id.toString())
                    // 单位名称
                    mViewModel.unitTypeNameField.set(unitTypeVO.name)

                }
            }
        }
    }

    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity(), true)
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                // 显示地址
                mBinding.sbAddress.setLeftTextColor(Color.parseColor("#666666"))
                mBinding.sbAddress.leftText = "$province $city $area"

                // 省市区id及详细地址
                mViewModel.provinceIDField.set(provincesVO!!.id.toInt())
                mViewModel.cityIDField.set(cityVO!!.id.toInt())
                mViewModel.areaIDField.set(areaVO!!.id.toInt())
                mViewModel.addressField.set("$province $city $area")
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }


    /**
     * 选择单位
     */
    private fun showUnitNameDialog() {
        observe(mViewModel.unitNameListEvent) { data ->
            Observable.fromIterable(data)
                .map { unitNameVO -> unitNameVO.name }.toList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    XPopup.Builder(this)
                        .asBottomList("选择单位", it.toTypedArray()
                        ) { position, text ->
                            val unitNameVO: UnitNameVO = data!![position]
                            // 选择单位id
                            mBinding.sbUnitName.setLeftTextColor(Color.parseColor("#666666"))
                            mBinding.sbUnitName.leftText = unitNameVO.name
                            mViewModel.selectUnitIdField.set(unitNameVO.id)
                            mViewModel.unitNameField.set(unitNameVO.name)
                            // 单位信息所携带得所属地址信息
                            mViewModel.provinceIDField.set(unitNameVO.provinceId.toInt())
                            mViewModel.cityIDField.set(unitNameVO.cityId.toInt())
                            mViewModel.areaIDField.set(unitNameVO.areaId.toInt())
                            mViewModel.addressField.set(unitNameVO.addressDetail)
                            mBinding.sbAddress.setLeftTextColor(Color.parseColor("#666666"))
                            mBinding.sbAddress.leftText = unitNameVO.addressDetail
                        }.show()
                })
        }
    }

}